List comprehension is a powerful and concise method for creating lists in Python that becomes essential the more you work with lists, and lists of lists.
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
my_new_list = [ expression for item in list ]
there are three parts in the expression above which are :
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
newlist = [x for x in fruits if x != "apple"]
in the example above, The condition if x != “apple” will return True for all elements other than “apple”
multiples_of_three = [ x*3 for x in range(10) ]
letters = [ name[0] for name in authors ]
where authors is a list of strings .
Example for Lower/Upper case converter using Python
lower_case = [ letter.lower() for letter in ['A','B','C'] ]
upper_case = [ letter.upper() for letter in ['a','b','c'] ]
Example for Printing numbers only from a given string
user_data = "Elvis Presley 987-654-3210"
phone_number = [ x for x in user_data if x.isdigit()]
isdigit() is a python built-in method that checks if the string character is a digit or not
for more understanding of list comprehension in Python:
for loop in list comprehension:
for loop with if condition: